package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对

        //对前端的代码进行比对
        password=DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 添加员工
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        //这里要把DTO转换成Employee实体对象,
        // 这样才能一一对应数据库中的employee表
        /**
         * 在两者对象有属性名完全一致下，就可以完成数据拷贝
         */
        Employee employee= new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        //以MD5的形式加密密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        employee.setStatus(StatusConstant.ENABLE);
        //通过
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());
//        System.out.println("当前线程id:"+Thread.currentThread().getId());
        employeeMapper.insertEmp(employee);
    }

    @Override
    public PageResult queryPage(EmployeePageQueryDTO employeePageQueryDTO) {
        //调用PageHelper插件来实现分页
        /**
         *  startPage这个方法用来帮忙计算第一个返回记录行的偏移量（索引）和返回记录行的最大数目（显示的个数）
         *  而且会在mybatis中自动生成动态sql的limit关键字
         */
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        /**
         *   编写sql查询方法以及sql语句,注意因为你用了PageHelper的插件，这里的返回值必须是Page类型，
         *   其实这个page类是PageHelper自带的类，封装了list集合,在getResult()方法上。
         */
        Page<Employee> page=employeeMapper.queryPage(employeePageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void update(Integer status, Long id) {
        //为了让以后编辑员工以及其他需要修改员工的操作时，用employee来封装状态和id以便
        // 采取通用的写法:动态sql写法
//        Employee employee = new Employee();
//        employee.setStatus(status);
//        employee.setId(id);
        //用构造器写法（因为加了@builder注解）
        Employee employee = Employee.builder().status(status).id(id).build();
        employeeMapper.update(employee);
    }

    @Override
    public Employee getById(Long id) {
        Employee employee= employeeMapper.getById(id);
        employee.setPassword("****");
        return employee;
    }

    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {
        /**
         *  这里要调用前面编写的启用禁用员工账号那个动态sql语句
         *  但是传入的类型不同，需要用到BeanUtils的属性拷贝
         */
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
//        employee.setUpdateTime(LocalDateTime.now());//更新时间
//        //利用在BaseContext中的设置线程存储变量ThreadLocal来获得当前登录用户id
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    /**
     * 编辑员工密码
     * @param passwordEditDTO
     */
    public void UpdatePassword(PasswordEditDTO passwordEditDTO) {
//        1.查询员工信息
//        Long empId = passwordEditDTO.getEmpId();
        Long empId = BaseContext.getCurrentId();
        Employee emp= employeeMapper.getById(empId);
        String oldPassword = passwordEditDTO.getOldPassword();
        String newPassword = passwordEditDTO.getNewPassword();
//        用MD5加密的密码才能匹配数据库的密码
        oldPassword=DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        newPassword=DigestUtils.md5DigestAsHex(newPassword.getBytes());
        if(empId==null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

//        2.比较员工的新密码与旧密码是否一致
//              输入的旧密码不能与新密码相同
        if(newPassword.equals(emp.getPassword())){
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_EDIT_FAILED);
        }


//              前端输入的旧密码不能与数据库的管理员密码匹配
        if (!oldPassword.equals(emp.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
//        3.修改密码
        Employee employee = new Employee();
        employee.setPassword(newPassword);
        employee.setId(empId);
        employeeMapper.update(employee);
    }

}
